package redis

import (
	"time"

	"github.com/gomodule/redigo/redis"
)

var Client *redis.Pool

func Init(host, port, password string, db, maxIdle, maxActive int) {

	// 建立连接池
	Client = &redis.Pool{

		MaxIdle:     maxIdle,
		MaxActive:   maxActive,
		IdleTimeout: 180 * time.Second,
		Dial: func() (redis.Conn, error) {
			c, err := redis.Dial("tcp", host+":"+port)
			if err != nil {
				return nil, err
			}

			if password != "" {
				_, err = c.Do("AUTH", password)
				if err != nil {
					c.Close()
					return nil, err
				}
			}

			// 选择db
			_, err = c.Do("SELECT", db)
			return c, err
		},
	}
}

func Set(key, value, expire string) (err error) {

	// 从池里获取连接
	rc := Client.Get()

	defer rc.Close()

	_, err = rc.Do("SET", key, value, "EX", expire)

	return
}

func Get(key string) (value string, err error) {
	// 从池里获取连接
	rc := Client.Get()

	defer rc.Close()

	value, err = redis.String(rc.Do("GET", key))
	return
}
